package com.itheima.d7_thread_pool;

import java.util.concurrent.*;

/**
 * 目标：掌握线程池的创建。
 * |---线程池执行Callable任务执行
 */
public class ThreadPoolTest2 {
    public static void main(String[] args) throws Exception {
        // 1、通过ThreadPoolExecutor创建一个线程池对象。
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,
                10,
                30,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        //2、处理任务
        //求1～n的和
        Future<Integer> f = pool.submit(new Calculator(100));
        //使用Future对象获取结果
        Integer sum = f.get();
        System.out.println("sum = " + sum);
    }
}

class Calculator implements Callable<Integer> {
    int n;

    public Calculator(int n) {
        this.n = n;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
}
